/**
 * Copyright (C) 2009 alex <me@alex.0x08.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uber.netbsd.community.i18n;

import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Locale;

/**
 * Обработка локалей
 * @author alex
 */
public class LocaleStore {

    /**
     * хранилище локалей
     */
    static final ImmutableList<LocaleInfo> locales = new ImmutableList.Builder<LocaleInfo>()
            .add(new LocaleInfo()
                .addCode("en")
                .addLocale(new Locale("en", "US"))
                .addDesc("English")
                .addIcon("/img/flags/usa.png"))
            .add(new LocaleInfo().addCode("ru")
                .addLocale(new Locale("ru", "RU"))
                .addDesc("Русский")
                .addIcon("/img/flags/russia.gif"))
          //  .add(new LocaleInfo().addCode("lv").addLocale(new Locale("lv","LV")).addDesc("Latvija").addIcon("/images/flags/latvia.png"))
            .build();

    static ImmutableBiMap<Locale, LocaleInfo> lo_map; // локаль к инфе
    static ImmutableBiMap<String, LocaleInfo> code_map; // код локали к инфе

    /**
     *  заполнение структур
     */
    static {


        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder<Locale, LocaleInfo>(),
                builder_code = new ImmutableBiMap.Builder<String, LocaleInfo>();

        for (LocaleInfo i : locales) {
            builder.put(i.getLocale(), i);
            builder_code.put(i.getCode(), i);
        }

        lo_map = builder.build();
        code_map = builder_code.build();


    }

    /**
     *  локаль по-умолчанию, будет выдаваться если у юзера неподдерживаемая локаль
     */
    private static LocaleInfo default_locale;

    /**
     *
     * @return локаль по-умолчанию
     */
    public LocaleInfo getDefault() {

        if (default_locale == null) {
            default_locale = code_map.get("en");
        }

        return default_locale;
    }

    /**
     *
     * @param loc локаль
     * @return информация о локали
     */
    public LocaleInfo getInfo(Locale loc) {

        if (loc.getCountry() == null || loc.getCountry().length() == 0) {

            loc = new Locale(loc.getLanguage(), loc.getLanguage().toUpperCase());
        }

        if (lo_map.containsKey(loc)) {
            return lo_map.get(loc);
        } else {
            return getDefault();
        }
    }

    /**
     *
     * @param code код локали
     * @return информация о локали
     */
    public LocaleInfo getInfo(String code) {

        if (code_map.containsKey(code)) {
            return code_map.get(code);
        } else {
            return getDefault();
        }
    }

    /**
     *
     * @param info объект с информацией о локали
     * @return локаль
     */
    public Locale getLocale(LocaleInfo info) {

        if (lo_map.containsValue(info)) {
            return lo_map.inverse().get(info);
        } else {
            return null;
        }
    }

    /**
     *
     * @return список всех поддерживаемых локалей
     */
    public List<LocaleInfo> getSupportedLocales() {
        return locales;
    }

    /**
     * синлтон
     */
    protected static LocaleStore instance;

    public static LocaleStore getInstance() {

        if (instance == null) {
            instance = new LocaleStore();
        }

        return instance;
    }
}
